package com.mego.weblink.activitys;


import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.mego.weblink.R;
import com.mego.weblink.database.dbmodel.SystemAllInfo;
import com.mego.weblink.database.manager.SystemCenter;
import com.mego.weblink.database.manager.ThmlogCenter;
import com.mego.weblink.utils.CrashHandler;
import com.mego.weblink.utils.GPSProvider;
import com.mego.weblink.utils.HttpRequest;
import com.mego.weblink.utils.LonLat;
import com.mego.weblink.utils.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import zuo.biao.library.interfaces.OnHttpResponseListener;
import zuo.biao.library.util.JSON;

public class WelcomeActivity extends Activity {

    private ProgressBar progress;
    String _welcome_notice = "連網失敗提示";
    private TextView bt_confirm;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    progress.setVisibility(View.GONE);
                    startApp();
                    break;
            }
        }
    };

    private void startApp() {
        Intent intent = new Intent(WelcomeActivity.this, MainActivity.class);
        intent.addFlags(Intent.FLAG_EXCLUDE_STOPPED_PACKAGES);
        startActivity(intent);
        WelcomeActivity.this.finish();
    }

    //    , Manifest.permission.ACCESS_COARSE_LOCATION
    private void permissonHandle() {
        //安卓6.0权限请求  本地数据库需要读写权限
        if (ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(WelcomeActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.RECEIVE_SMS,
                    Manifest.permission.READ_SMS, Manifest.permission.FOREGROUND_SERVICE}, 111);
        } else {
            AppContext.getInstances().setDatabase();    //初始化数据库
            start();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean writeAccepted = false;
        switch (requestCode) {
            case 111:
                writeAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (writeAccepted) {
                    AppContext.getInstances().setDatabase();    //初始化数据库
                    start();
                } else {
                    moveTaskToBack(false);//应用退到后台
                    System.exit(0);
                }
                break;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        SharedPreferences sp = getSharedPreferences(
                "colininfo", Context.MODE_PRIVATE);
        boolean startfromservice = sp.getBoolean("startfromservice", false);
        if (startfromservice) {
//            moveTaskToBack(false);
        }

        Log.i("MainService", "WelcomeActivity-onCreate");

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        setContentView(R.layout.welcome);

        progress = (ProgressBar) this.findViewById(R.id.progress);
        bt_confirm = (TextView) findViewById(R.id.bt_confirm);
        bt_confirm.setVisibility(View.GONE);
        SystemAllInfo welcome_btn = SystemCenter.getInstance().getSysInfo("welcome_btn");
        if (welcome_btn != null) {
            String strwelcome_btn = welcome_btn.getContent();
            bt_confirm.setText(strwelcome_btn);

        }
        SystemAllInfo welcome_notice = SystemCenter.getInstance().getSysInfo("welcome_notice");
        if (welcome_notice != null) {
            _welcome_notice = welcome_notice.getContent();
        }

        CrashHandler crashHandler = CrashHandler.getInstance();
        crashHandler.init(getApplicationContext());
        Thread.setDefaultUncaughtExceptionHandler(crashHandler);

        permissonHandle();

    }

    private void start() {
        onlwcs(null);

//        new Thread() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(1000);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//
//                Message msg = new Message();
//                msg.what = 1;
//                handler.sendMessage(msg);
//
//            }
//        }.start();
    }

    void deepFile(Context ctxDealFile, String path, boolean needRecopy) {
        try {
            String RUNDIR0 = Environment.getExternalStorageDirectory() + "/";
            String str[] = ctxDealFile.getAssets().list(path);
            if (str.length > 0) {//如果是目录
                File file = new File(RUNDIR0 + path);
                file.mkdirs();
                for (String string : str) {
                    path = path + "/" + string;
                    deepFile(ctxDealFile, path, needRecopy);
                    path = path.substring(0, path.lastIndexOf('/'));
                }
            } else {//如果是文件
                InputStream is = ctxDealFile.getAssets().open(path);
                File outFile = new File(RUNDIR0 + path);
                if (!needRecopy && outFile.exists()) {
                    return;
                }
                FileOutputStream fos = new FileOutputStream(outFile);
                byte[] buffer = new byte[1024];
                int count = 0;
                while (true) {
                    count++;
                    int len = is.read(buffer);
                    if (len == -1) {
                        break;
                    }
                    fos.write(buffer, 0, len);
                }
                is.close();
                fos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onlwcs(View v) {
//        if (!Utils.isNetConnected()) {
//            bt_confirm.setVisibility(View.VISIBLE);
//            Toast.makeText(this, _welcome_notice, Toast.LENGTH_SHORT).show();
//            return;
//        }

        progress.setVisibility(View.VISIBLE);
        String imei = Utils.getIMEI(this);
        try {
            HttpRequest.postlwcs(imei, 0, new OnHttpResponseListener() {
                @Override
                public void onHttpResponse(int requestCode, String resultJson, Exception e) {
                    if (resultJson == null) {
                        //未联网
                        progress.setVisibility(View.GONE);
                        bt_confirm.setVisibility(View.VISIBLE);
                        Toast.makeText(WelcomeActivity.this, _welcome_notice, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    JSONObject jsonObject = JSON.parseObject(resultJson);
                    int code = 0;
                    if (jsonObject != null) {
                        code = jsonObject.getInteger("code");
                    }

                    if (code == 1) {
                        JSONObject data = jsonObject == null ? null : jsonObject.getJSONObject("data");
                        String welcome_btn = data.getString("welcome_btn");
                        String welcome_notice = data.getString("welcome_notice");

                        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "welcome_btn", welcome_btn));
                        SystemCenter.getInstance().saveSysInfo(new SystemAllInfo(null, "welcome_notice", welcome_notice));

                        Message msg = new Message();
                        msg.what = 1;
                        handler.sendMessage(msg);
                    }
                }
            });
        } catch (Exception e1) {
//            showShortToast(e1.getMessage());
            bt_confirm.setVisibility(View.VISIBLE);
            Toast.makeText(this, _welcome_notice, Toast.LENGTH_SHORT).show();
        }
    }


}